<?php

/**
 * Permite administrar el crud de Patologias
 */
class PatologiasController extends AweController {

    /**
     * @var string the default layout for the views. Defaults to '//layouts/column2', meaning
     * using two-column layout. See 'protected/views/layouts/column2.php'.
     */
    public $layout = '//layouts/column2';
    public $defaultAction = 'admin';

    public function filters() {
        return array(
            array('CrugeAccessControlFilter'),
        );
    }

    /**
     * Displays a particular model.
     * @param integer $id the ID of the model to be displayed
     */
    public function actionView($id) {
        if (Yii::app()->user->checkAccess("supervisor")) {
            $this->render('view', array(
                'model' => $this->loadModel($id),
            ));
        } else if (Yii::app()->user->checkAccess("institucion")) {
            $data = Patologias::model()->de_institucion($id)->findAll();
            if (!empty($data)) {
                $this->render('view', array(
                    'model' => $this->loadModel($id),
                ));
            } else {
                $this->redirect(array('../ninio/institucion/contenidos'));
            }
        }
    }

    /**
     * Creates a new model.
     * If creation is successful, the browser will be redirected to the 'view' page.
     */
    public function actionCreate($id = null) {
        $model = new Patologias;


        if (isset($_POST['Patologias'])) {
            $model->attributes = $_POST['Patologias'];
            $result = Patologias::model()->validarPatologiaUnica($_POST['Patologias']['ninios_id'])->findAll();
            if (empty($result)) {
                if ($model->save()) {
                    $this->redirect(array('view', 'id' => $model->id));
                }
            } else {
                Yii::app()->user->setFlash('error', 'Ya existen h&aacute;bitos alimenticios registrados para el infante');
                $this->redirect('admin');
            }
        }
        if ($id != null) {
            $result = Patologias::model()->validarPatologiaUnica($id)->findAll();
            if (empty($result)) {
                $model->ninios_id = $id;
                $this->render('create', array(
                    'model' => $model,
                ));
            } else {
                $this->redirect(array('update', 'id' => $result[0]['oldValues']['id']));
            }
        } else {
            $this->render('create', array(
                'model' => $model,
            ));
        }
    }

    /**
     * Updates a particular model.
     * If update is successful, the browser will be redirected to the 'view' page.
     * @param integer $id the ID of the model to be updated
     */
    public function actionUpdate($id) {
        $model = $this->loadModel($id);
        if (isset($_POST['Patologias'])) {
            $model->attributes = $_POST['Patologias'];
            if ($model->save()) {
                $this->redirect(array('view', 'id' => $model->id));
            }
        }
        if (Yii::app()->user->checkAccess("admin")) {
            $this->render('update', array(
                'model' => $model,
            ));
        } else if (Yii::app()->user->checkAccess("institucion")) {
            $data = Patologias::model()->de_institucion($id)->findAll();
            if (!empty($data)) {
                $this->render('update', array(
                    'model' => $model,
                ));
            } else {
                $this->redirect(array('../ninio/institucion/contenidos'));
            }
        }
    }

    /**
     * Deletes a particular model.
     * If deletion is successful, the browser will be redirected to the 'admin' page.
     * @param integer $id the ID of the model to be deleted
     */
    public function actionDelete($id) {
        if (Yii::app()->request->isPostRequest) {
            // we only allow deletion via POST request
            $this->loadModel($id)->delete();

            // if AJAX request (triggered by deletion via admin grid view), we should not redirect the browser
            if (!isset($_GET['ajax']))
                $this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('admin'));
        } else
            throw new CHttpException(400, 'Invalid request. Please do not repeat this request again.');
    }

    /**
     * Manages all models.
     */
    public function actionAdmin() {
        $model = new Patologias('search');
        $model2 = new Patologias('search');
        $model->unsetAttributes(); // clear any default values
        $model2->unsetAttributes(); // clear any default values
        if (isset($_GET['Patologias'])) {
            $model->attributes = $_GET['Patologias'];
            $model2->attributes = $_GET['Patologias'];
        }
        $query = $model->contarDatos();
        if (Yii::app()->user->checkAccess("supervisor")) {
            if ($query > 0) {
                $this->render('admin', array(
                    'model' => $model, 'model2' => $model2
                ));
            } else {
                if (Yii::app()->user->checkAccess("admin")) {
                    $this->render('empty', array());
                } else {
                    Yii::app()->user->setFlash('error', 'Todavia no se ha registrado h&aacute;bitos alimenticios para los infantes');
                    $this->redirect(array('../ninio/institucion/contenidos'));
                }
            }
        } else if (Yii::app()->user->checkAccess("institucion")) {
            $data = Patologias::model()->de_institucion()->findAll();
            if (!empty($data)) {
                $this->render('admin', array(
                    'model' => $model, 'model2' => $model2
                ));
            } else {
                $this->render('empty', array());
            }
        }
    }

    /**
     * Returns the data model based on the primary key given in the GET variable.
     * If the data model is not found, an HTTP exception will be raised.
     * @param integer the ID of the model to be loaded
     */
    public function loadModel($id, $modelClass = __CLASS__) {
        $model = Patologias::model()->findByPk((int) $id);
        if ($model === null)
            throw new CHttpException(404, 'The requested page does not exist.');
        return $model;
    }

    /**
     * Performs the AJAX validation.
     * @param CModel the model to be validated
     */
    protected function performAjaxValidation($model, $form = null) {
        if (isset($_POST['ajax']) && $_POST['ajax'] === 'patologias-form') {
            echo CActiveForm::validate($model);
            Yii::app()->end();
        }
    }

}
